from django.shortcuts import render
from django.core.cache import cache
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from nav import models, serializer


# Create your views here.
class HeaderView(APIView):
    def get(self, request):
        key="headnav"
        res=cache.get(key)
        if res:
            return Response({'code':200,'msg':'ok','data':res})
        res=models.NavModel.objects.filter(is_http=True,position=0).order_by('order')
        ser=serializer.NavSerializer(res,many=True)
        cache.set(key,ser.data,60*60*24)
        return Response({'code':200,'msg':'ok','data':ser.data})
class FooterView(APIView):
    def get(self, request):
        key="footernav"
        res=cache.get(key)
        if res:
            return Response({'code':200,'msg':'ok','data':res})
        res=models.NavModel.objects.filter(is_http=True,position=1).order_by('order')
        ser=serializer.NavSerializer(res,many=True)
        cache.set(key,ser.data,60*60*24)
        return Response({'code':200,'msg':'ok','data':ser.data})
class BannerView(ListAPIView):
    queryset = models.Banner.objects.filter(flag=True).order_by('order')
    serializer_class = serializer.BannerSerializer
from django.core.files.storage import default_storage
class uploadFile(APIView):
    def post(self,request):
        file=request.data.get('file')
        type=['jpg', 'jpeg', 'png']
        if file.name.split('.')[-1] not in type:
            return Response({'code':400,'msg':'文件类型错误'})
        if file.size  > 10240 * 1024 * 2:
            return Response({'code':400,'msg':'文件过大'})
        uploadfile=default_storage.save(file.name,file)
        url=default_storage.url(uploadfile)
        return Response({'url':url})


